/* eslint-disable react-refresh/only-export-components */
import type {FC} from "react";
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input ,Space,message} from 'antd';
import { Link,useSubmit,useNavigation, redirect} from "react-router-dom";
import type {ActionFunctionArgs} from "react-router-dom";
import {regApi} from '@/api/auth-api'
import to from 'await-to-js'


const Reg:FC = () =>{
  const submit = useSubmit()
    const onFinish = (values: RegForm) => {
      //参数1为提交给action的数据 
      //参数2为配置对象，用来指定提交的method和action地址
      submit(values,{
        method:'POST',
        action:'/reg'
      })
      }
      const navigation = useNavigation()

    return (
        <Form
        onFinish={onFinish}
        size="large"
      >
        <Form.Item
          name="username"
          rules={[{ 
            required: true, message: '请输入用户名'},
            {pattern:/^[a-zA-Z0-9]{1,10}$/,message:'用户名必须是1-10位的非空字符'}
          ]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码' },
            {pattern:/^\S{6,15}$/,message:'密码必须是6-15位非空字符'}
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="Password"
          />
        </Form.Item>

        <Form.Item
          name="repassword"
          dependencies={['password']}
          validateFirst
          rules={[{ required: true, message: '请确认密码' },
            {pattern:/^\S{6,15}$/,message:'密码必须是6-15位非空字符'},
            ({getFieldValue})=>({
              validator(_,value) {
                //value是当前标单的值(第二个密码框的值)
                //getFieldValue('password')为获取指定表单项的值，根据name
                if(value === getFieldValue('password')) return Promise.resolve()
                  return Promise.reject(new Error('两次密码不一致'))
              }
            })
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="Confirm Password"
          />
        </Form.Item>
        
        <Form.Item>
          <Space direction="vertical">
            <Button type="primary" htmlType="submit" loading={navigation.state !== 'idle' && {delay:200}}>
                注册
            </Button>
            <div>
            Or <Link to="/login">登录</Link>
            </div>
          </Space>
        </Form.Item>
      </Form>
    )
}



//定义并导出路由的action函数
export const action =async({ request }:ActionFunctionArgs) =>{
  const fd = await request.formData()
  //调用注册接口
  const [err] = await to(regApi(fd))
 
  if(err) return null
  
  message.success('注册成功')
  return redirect('/login?uname=' + fd.get('username'))
}

export default Reg